package com.rabbitmq.transaction;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.utils.RabbitMQUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Send {
    public static void main(String[] args) {
        //创建工厂对象用于指定链接的信息
        Connection connection = null;
        Channel channel = null;
        //创建链接以及通道,并添加异常处理同时在try..catch执行完成后自动释放资源
        try {
            connection = RabbitMQUtils.getConnection();
            channel = connection.createChannel();
            String queueName = "transactionQueue";
            channel.queueDeclare(queueName, true, false, false, null);
            String exchangeName = "directExchange";
            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueBind(queueName, exchangeName, "transactionKey");

            String message = "事务的测试消息";
            //开启事务,开启事务后必须要显示的调用txCommit或txRollback方法
            channel.txSelect();
            channel.basicPublish(exchangeName, "transactionKey", null, message.getBytes());
            System.out.println("消息发送成功");
            //提交事务,将当前通道中当前事务中的所有消息全部写入到MQ服务器同时会清空内存中的这些消息并结束当前事务
            channel.txCommit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            RabbitMQUtils.closeConnectionAndChanel(channel, connection);
        }
    }
}
